package com.doctor.ui.consulting;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.doctor.adapter.BookServiceAdapter;
import com.doctor.adapter.BookServiceAdapter.BookServiceAdapterCallback;
import com.doctor.bean.BookServiceBean;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.MyApplication;
import com.doctor.comm.DialogHelper.DialogSelectCallback;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.comm.FragmentHelper;
import com.doctor.database.DbOperator;
import com.doctor.net.NetUtil;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.LoginActivity;
import com.doctor.ui.R;
import com.doctor.view.PullToRefreshListView;
import com.doctor.view.PullToRefreshListView.OnRefreshListener;

public class BookServiceFrag extends BaseFragment{

	/**
	 * 预约服务
	 */
	
	private BookServiceFragCallback callback;
	
	private Context context;
	private String[] operation={"修改","删除","取消"};
	private PullToRefreshListView listView;
	private BookServiceAdapter adapter;
	private View listFoot;
	private TextView footMore;
	private ProgressBar footProgress;
	private LinearLayout addBtn;    //添加按钮
	//从第1行开始查询
	private int fromRow=0;
	private AddBookServiceFrag addBookServiceFrag;
	private List<BookServiceBean> beanList=new ArrayList<BookServiceBean>();
	private ModifyBookServiceFrag modifyBookServiceFrag;
	//用户的省份、城市、县信息
	private String province, city, county;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		String[] region = DbOperator.getInstance(getActivity()).selectUserRegion();
		if (region != null) {
			province = region[0] != null && region[0].trim().length() > 0 ? region[0] : null;
			city = region[1] != null && region[1].trim().length() > 0 ? region[1] : null;
			county = region[2] != null && region[2].trim().length() > 0 ? region[2] : null;
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		context=getActivity();
		View view=inflater.inflate(R.layout.book_service, container, false);
		initiaView(view);
		getData();
		
		callback.onBookService();
		return view;
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	
	public interface BookServiceFragCallback{
		public void onBookService();
	}
	
	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		try {
			callback=(BookServiceFragCallback) activity;
		} catch (ClassCastException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		addBtn=(LinearLayout) view.findViewById(R.id.addBtn);
		addBtn.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				addBookServiceFrag=null;
				addBookServiceFrag=new AddBookServiceFrag();
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, addBookServiceFrag).addToBackStack(null).commit();
			}
		});
		
		listView=(PullToRefreshListView) view.findViewById(R.id.listView);
		listFoot=View.inflate(getActivity(), R.layout.listview_footer, null);
		footMore=(TextView) listFoot.findViewById(R.id.listview_foot_more);
		footProgress=(ProgressBar) listFoot.findViewById(R.id.listview_foot_progress);
		// 添加底部视图 必须在setAdapter前
		listView.addFooterView(listFoot);
		
		beanList.clear();
		beanList=new ArrayList<BookServiceBean>();
		fromRow=0;
		adapter=new BookServiceAdapter(context, beanList, new BookServiceAdapterAchieve());
		listView.setAdapter(adapter);
		
		listView.setOnScrollListener(new OnScrollListener() {			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				listView.onScrollStateChanged(view, scrollState);		
				if (adapter.getCount()==0) {
					return;
				}
				//判断是否滚动到底部
				boolean scrollEnd=false;
				try {
					if (view.getPositionForView(listFoot)==view.getLastVisiblePosition()) {
						scrollEnd=true;
					}
				} catch (Exception e) {
					scrollEnd=false;
					e.printStackTrace();					
				}
				
				if (scrollEnd && scrollState==SCROLL_STATE_TOUCH_SCROLL) {
					//下拉刷新
					footMore.setText(R.string.loading_data);
					footProgress.setVisibility(View.VISIBLE);
					footMore.setVisibility(View.VISIBLE);
					fromRow=adapter.getCount();
					freshData(fromRow);
				}	
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				listView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		
		listView.setOnRefreshListener(new OnRefreshListener() {			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				//上拉刷新
				listView.onRefreshComplete();
				fromRow=0;
				freshData(fromRow);
			}
		});
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg1==listFoot) {
					//点击底部栏无效
					return true;
				}
				final BookServiceBean bean=(BookServiceBean) arg1.getTag(R.id.bean_tag);				
				DialogHelper.selectDialog(context, null, operation, new DialogSelectCallback() {					
					@Override
					public void onDialogSelected(int position1) {
						// TODO Auto-generated method stub
						if (position1==0) {
							//修改
							modifyBookServiceFrag=null;
							modifyBookServiceFrag=new ModifyBookServiceFrag();
							
							Bundle bundle=new Bundle();
							bundle.putSerializable(ConstConfig.BEAN, bean);
							//fragment间传递数据
							modifyBookServiceFrag.setArguments(bundle);
							FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
							FragmentHelper.setFragSwitchAnimation(transaction);
							transaction.replace(R.id.frag_container, modifyBookServiceFrag).addToBackStack(null).commit();
						} else if (position1==1) {
							DialogHelper.noticeDialog(context, null, new NoticeDialogCallback() {								
								@Override
								public void onClicked(int position2) {
									// TODO Auto-generated method stub
									if (position2==1) {
										//删除
										int row=DbOperator.getInstance(context).deleteData(ConstConfig.HOSPITAL_TABLE, bean.getId());
										if (row>0) {
											adapter.remove(bean);
										}
									}
								}
							});
						}
					}
				});
				return true;
			}
		});
		
		freshData(fromRow);
	}
	
	
	
	
	
	
	private class BookServiceAdapterAchieve implements BookServiceAdapterCallback{
		@Override
		public void onPhoneClicked(String phone) {
			// TODO Auto-generated method stub
			TelephonyManager telManager=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);			
			if (telManager.getSimState()==TelephonyManager.SIM_STATE_ABSENT) {
				Toast.makeText(context, "未插入SIM卡！", Toast.LENGTH_SHORT).show();
			} else if (telManager.getSimState()==TelephonyManager.SIM_STATE_READY) {
				if (null!=phone && !"".equals(phone)) {
					startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone)));
				} else {
					Toast.makeText(context, "没有设置电话！", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(context, "请确保SIM卡状态良好！", Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onSpecialNumClicked(String specialNum) {
			// TODO Auto-generated method stub
			TelephonyManager telManager=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);			
			if (telManager.getSimState()==TelephonyManager.SIM_STATE_ABSENT) {
				Toast.makeText(context, "未插入SIM卡！", Toast.LENGTH_SHORT).show();
			} else if (telManager.getSimState()==TelephonyManager.SIM_STATE_READY) {
				if (null!=specialNum && !"".equals(specialNum)) {
					startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+specialNum)));
				} else {
					Toast.makeText(context, "没有设置专号！", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(context, "请确保SIM卡状态良好！", Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onWebSiteClicked(String url) {
			// TODO Auto-generated method stub
			if (!NetUtil.hasNetwork(context)) {
				Toast.makeText(context, "请连接网络！", Toast.LENGTH_SHORT).show();
				return;
			}
			if (url==null || "".equals(url.trim())) {
				Toast.makeText(context, "未填写平台信息！", Toast.LENGTH_SHORT).show();
				return;
			}
			
			Intent intent = new Intent();        
	        intent.setAction("android.intent.action.VIEW");    
	        Uri content_url;
	        
			if (url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) {
				content_url = Uri.parse(url); 
			} else {
				content_url = Uri.parse("http://"+url); 
			}		
			intent.setData(content_url);            
	        startActivity(intent);
		}
		
	}
	
	
	
	
	//刷新数据
	private final void freshData(final int fromRow){
		if (fromRow<=0) {
			adapter.clear();
			//上拉刷新后id从头开始计数
			this.fromRow=0;
			adapter.notifyDataSetChanged();
		}
		
		new Thread() {
			public void run() {
				try {
					sleep(DbOperator.delayTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				final List<BookServiceBean> list=DbOperator.getInstance(context).selectBookServiceData(fromRow, province, city, county);
				getActivity().runOnUiThread(new Runnable() {					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (list!=null && list.size()>0) {
							adapter.add(list);
						}			
						footMore.setText(R.string.more);
						footMore.setVisibility(View.GONE);
						footProgress.setVisibility(View.GONE);
					}
				});
			}
		}.start();	
	}	
	
	
	
	
	
}
